<?php
namespace control;
/*
*生产返工单类
*/

class machiningReworkOrderClass extends adIndexClass
{
    private const table = 'machining_rework_order';
    private const page = 'machiningReworkOrder';
    private const title = '生产返工单';
    public array $stateOption = ['草稿', '待确认', '已确认'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "单据编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'process'  => [
                        'name'  => '返工工序',
                        'width' => 200,
                    ],
                    'backTime'         => [
                        'name'  => '返工时间',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'num'          => [
                        'name'  => '返工数量',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 200,
                    ],
                    'sourceOrder'          => [
                        'name'  => '关联源单',
                        'width' => 200,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "状态" => checkbox(array('name' => 'state', 'value' => $this->stateOption, 'checked' => ['草稿', '待确认'])),
                ],
                [
                    '单据编号'  => text(array('name' => 'orderNo')),
                    "工序" => selectMultiple(array('name' => 'processId', 'sqlField' => "name", 'sqlId' => 'id', 'table' => 'process', 'where' => "coid = '" . self::$coid . "' order by time asc", 'class' => 'width200')),
                    '产品名称' => text(array('name' => 'materialName')),
                ],
                [
                    "返工日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*行政人事-出差记录-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . $this->get('cla');
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= " <span onclick=\"batchPrint('" . $this->get('cla') . "')\" class='spanButton'>批量打印</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*行政人事-出差记录-查询结果*/
    public function homeSearch()
    {
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
            "processId" => $this->post('processId'),
        );
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
        );
        //初始化
        $and = "";
        $mAnd = '';
        if ($this->post('machiningOrderNo')) {
            if (optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard') {
                $and .= " and sourceId in (select id from machining_card_detail where orderId in (select id from machining_card where  coid = '" . self::$coid . "' and orderNo like '%" . $this->post('machiningOrderNo') . "%'))";
            } else {
                $and .= " and sourceId in (select id from machining_send_order where  coid = '" . self::$coid . "' and orderNo like '%" . $this->post('machiningOrderNo') . "%')";
            }
        }
//        if ($this->post('brand')) {
//            $mAnd = " and brand like '%" . $this->post('brand') . "%'";
//        }
//        if ($this->post('materialName')) {
//            $mAnd = " and name like '%" . $this->post('materialName') . "%'";
//        }
//        if ($mAnd) {
//            $and .= " and  materialId in (select id from material where coid = '" . self::$coid . "' {$mAnd})";
//        }
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), field: 'backTime');
        }
        if ($this->post('state')) {
            //单据日期
            $and .= " and state in ('" . implode("','", $this->post('state')) . "')";
        }
        //如果没有查看所有员工请假记录的权限
        if (!$this->power(self::page, "seeAll")) {
            $and .= $this->seeSelf(self::page);
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";

        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            if ($this->power(self::page,'print')){
                $dominate['print'] = array('title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')");
            }
            if ($array['state'] == '已确认') {
                unset($dominate['edit']);
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'sourceOrder':
                        if ($array['sourceTable'] == 'machining_card_detail') {
                            $machining_card_detail = query('machining_card_detail', "id = '$array[sourceId]'");
                            $sourceOrder = query('machining_card', "id = '$machining_card_detail[orderId]'");
                        } else {
                            $sourceOrder = query('machining_send_order', "id = '$array[sourceId]'");
                        }
                        $row[] = $sourceOrder['orderNo'];
                        break;
                    case 'process':
                        $process = query('process', "id = '$array[processId]'");
                        $row[] = $process['name'];
                        break;
                    case 'num':
                        $row[] = self::lostZero($array['num'], 'numPrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
    /**
     * 编辑
     *
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id') ?: self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        if ($info['sourceTable'] == 'machining_card_detail') {
            $machining_card_detail = query('machining_card_detail', "id = '$info[sourceId]'");
            $sourceOrder = query('machining_card', "id = '$machining_card_detail[orderId]'");
        } else {
            $sourceOrder = query('machining_send_order', "id = '$info[sourceId]'");
        }
        $process = query('process', "id = '$info[processId]'");
        $materialName = $sourceOrder['id'] ? materialClass::getName($sourceOrder['materialId']) : '';
        $line = query('product_line', "id = '$sourceOrder[lineId]'");
        $lineName = $line['workshop'] . '-' . $line['name'];
        //表单
        $html = $this->layerEdit([
            "table" => [
                array(
                    must . "生产派工单号/生产流转卡：" => hidden(array('name' => 'sourceId', 'value' => $info['sourceId'])) .
                        "<span id='machiningOrder'>{$sourceOrder['orderNo']}</span><span class='del-row-button' style='margin-left: 5px;cursor: pointer' onclick=\"layer('{$this->get('cla')}','addMaterial',{})\">选择</span>",
                    must . "工序：" => "<div id='process'>" . $process['name'] . "</div>" . hidden(array('name' => 'processId', 'value' => $process['id'])),

                ),
                array(
                    "生产线：" => "<span id='line'>{$lineName}</span>",
                ),
                array(
                    "物料：" => "<span id='material'>{$materialName}</span>",
                ),
                array(
                    must . "返工数量：" => text(array("name" => "num", 'other' => self::digitalFiltering('numPrecision'), "value" => self::lostZero($info['num'], 'numPrecision'))),
                    "返工时间：" => text(array("name" => "backTime", 'laydate' => ['type' => 'datetime'], "value" => self::null($info['backTime'], false))),
                ),
                array(
                    "备注：" => textarea(array("name" => "text", "value" => $info['text'])),
                ),
            ],
            'hidden' => hidden(array('name' => 'id', 'value' => $id)),
        ]);
        $html .= $this->js();
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 350, "html" => $html));
    }

    public function js(): string
    {
        return <<<efo
<style>
.item_row{margin: 5px 0}
.layerList > ul > li:nth-child(2n-1) {width: 190px;}
.left-bottom {
    left: 234px;
}
</style>
<script>
          //选择生产产品
    function addMaterial(){
             $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMaterialEdit',$("form[name='mxForm']").serialize(),function(res) {
                 if (res.warn ==2){
                    $('#machiningReworkOrderAddMaterial').hide();
                    $("[name='num']").val(res.planNum);
                    $("#process").empty().append(res.process);
                    $("[name='processId']").val(res.processId);
                    $("#machiningOrder").html(res.orderNo);
                    $("#line").html(res.lineName);
                    $("#material").html(res.materialName);
                    $("[name='sourceId']").val(res.id);
                 }else{
                     msg(res.warn);
                 }
            },'json');
    }
</script>
efo;
    }

    /*编辑*/
    public function editEdit()
    {

        $id = $this->post('id') ?: self::getId();
        //赋值
        $field = array(
            "backTime" => $this->post('backTime'),
            "sourceId" => $this->post('sourceId'),//备注
            "text" => $this->post('text'),//备注
            "num" => $this->post('num') ? self::formattingFigure($this->post('num'), 'numPrecision') : '',
        );
        $isProductCard = optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard';
        if ($isProductCard) {
            $machining_card_detail = query('machining_card_detail', "id = '$field[sourceId]'");
            $field['sourceId'] = $machining_card_detail['id'];
            $sourceOrder = query('machining_card', "id = '$machining_card_detail[orderId]'");
            $field['routingMxId'] = $machining_card_detail['routingMxId'];
            $field['processId'] = $machining_card_detail['processId'];
            $field['sourceTable'] = 'machining_card_detail';
        } else {
            $sourceOrder = query('machining_send_order', "id = '$field[sourceId]'");
            $field['sourceId'] = $sourceOrder['id'];
            $field['routingMxId'] = $sourceOrder['routingMxId'];
            $field['processId'] = $sourceOrder['processId'];
            $field['sourceTable'] = 'machining_send_order';
        }

        $field['materialId'] = $sourceOrder['materialId'];
        $field['routingId'] = $sourceOrder['routingId'];
        $field['unit'] = $sourceOrder['unit'];
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "权限不足";
        } elseif ($info['state'] == '已确认') {
            $json['warn'] = '此报工已确认，不能编辑';
        } else {
            if (empty($info['id'])) {
                $userNo = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'SCFG' . date('Ymd', strtotime(($sourceOrder['recordDate']?:$this->date))),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => " and coid = '" . self::$coid . "'",
                ], $field);
                $field = array_merge($field, array("id" => $id, 'coid' => self::$coid, 'orderNo' => $userNo, 'state' => '草稿', 'stid' => $this->control['stid']));
                $json['warn'] = insert(array("table" => self::table, "field" => $field));
            } else {
                $json['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$info[id]'"));
            }

            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                if ($json['warn'] == '新增成功') {
                    self::insertOperateLog($id,self::title,"新建");
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "ID：" . $id;
                $this->logText(array("type" => self::page, "text" => $text));
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }

        $json['href'] = root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $id;
        resp:
        return json_encode($json, 320);
    }


    /*出差详情*/
    public function detail(): string
    {
        //定义参数
        if (empty($this->get('id'))) {
            $html = '未找到此' . self::title;
        } else {
            $info = query(self::table, " id = '" . $this->get('id') . "' ");
            if (empty($info['id'])) {
                $html = "未找到此记录";
            } else {
                //菜单
                $data = array(
                    "id" => $info['id'],
                );

                $button = [];
                if ($info['state'] == '草稿') {
                    if ($this->power(self::page, "edit")) {
                        //按钮
                        $button[] = [
                            "name" => "提交",
                            "type" => "弹出层",
                            "cla" => $this->get('cla'),
                            "fun" => "operate",
                            "post" => ["act" => 'commit', "id" => $info['id']],
                            'style' => 'li-btn-blue-bg',
                        ];
                        //按钮
                        $button[] = [
                            "name" => "编辑",
                            "type" => "弹出层",
                            "cla" => $this->get('cla'),
                            "fun" => "edit",
                            "post" => ["id" => $info['id']],
                        ];
                    }
                    if ($this->power(self::page, "del")) {
                        //按钮
                        $button[] = [
                            "name" => "删除",
                            "type" => "弹出层",
                            "cla" => $this->get('cla'),
                            "fun" => "operate",
                            "post" => ["act" => 'del', "id" => $info['id']],
                        ];
                    }
                }

                if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                    $button[] = [
                        "name" => "复核",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'confirm', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                }
                if ($this->power(self::page, "cancel") && $info['state'] != '草稿') {
                    $button[] = [
                        "name" => "撤回",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'cancel', "id" => $info['id']],
                    ];
                }
                if ($this->power(self::page,'print')){
                    $button[] = [
                        "name" => "打印",
                        "type" => "点击事件",
                        "fun" => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$info['id']}')",
                    ];
                }
                //操作记录
                $button[] = self::operateLogBut($info['id'],1);

                if ($info['sourceTable'] == 'machining_card_detail') {
                    $machining_card_detail = query('machining_card_detail', "id = '$info[sourceId]'");
                    $sourceOrder = query('machining_card', "id = '$machining_card_detail[orderId]'");
                } else {
                    $sourceOrder = query($info['sourceTable'], "id = '$info[sourceId]'");
                }
                $line = query('product_line', "id = '$sourceOrder[lineId]'");
                $process = query('process', "id = '$info[processId]'");

                //生成表单
                $data['button'] = $this->tableShowButton($button);
                $data['html'] = $this->tableShow(array(
                    "基本信息" => array(
                        array(
                            "生产返工单号" => $info['orderNo'],
                            "派工单号/生产流转卡单号" => $sourceOrder['orderNo'],

                            '生产线' => $line['workshop'] . '-' . $line['name'],
                            "返工工序" => $process['name'],
                        ),
                        array(
                            "返工数量" => self::lostZero($info['num'], 'numPrecision') . $info['unit'],
                            "返工时间" => $info['backTime'],
                            "物料" => materialClass::getName($info['materialId']),
                        ),
                        array(
                            "备注" => pre($info['text']),
                        ),
                    ),
                    '系统信息' => array(
                        array(
                            "创建人" => self::findStaff($info['stid']),
                            "创建时间" => $info['time'],
                            "状态" => $info['state']
                        ),
                    ),
                ));
                //生成页面
                $html = $this->tab($data);
            }
        }
        //返回
        return $html;
    }


    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time,
        ];

        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此' . self::title;
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = '此' . self::title . '不是待确认状态，不能确认';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])) {
                    self::insertOperateLog($info['id'],self::title,"提交、复核");
                }else{
                    self::insertOperateLog($info['id'],self::title,"复核");
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '确认成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '草稿',
            'checkId' => '',
            'confirmTime' => '',
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此生产返工单';
        } elseif ($info['state'] != '已确认') {
            $json['warn'] = '此生产返工单不是已确认状态，无需撤回';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                self::insertOperateLog($info['id'],self::title,"撤回");
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '撤回成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }
    /**
     * Desc : 提交前数据验证
     * User : you name
     * Date : 2023-11-17 16:04
     * @param $info
     * @return string|bool
     */
    public function dataValidation($info): string|bool
    {
        $annotation = [
            "sourceId" => '来源单据',
            "num" => '返工数量',
            "processId" => '工序',
            "routingId" => '工艺路线',
            "routingMxId" => '工艺路线明细',
            "unit" => '单位',
        ];
        $rules = [
            "sourceId" => 'required',
            "num" => 'required|numeric',
            'processId' => 'required',
            "routingId" => 'required',
            'routingMxId' => 'required',
            "unit" => 'required',
        ];

        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($info, $rules)->isOk();
        if ($result === false) {
            return $vt->getErrs()[0];  // 多个规则提示最前面一条
        }
        $reportNum = find(array('table' => 'process_report', 'where' => "sendId = '$info[sourceId]' and state = '已确认'", 'sum' => "yield"));
        //加上已经在返工单中的数量
        $reportNum -= find(array('table' => self::table, 'where' => "sourceId = '$info[sourceId]'  and id !='$info[id]'", 'sum' => "num"));
        if ($info['num'] > $reportNum) {
            return '返工数量不能超过报工数量';
        }
        return true;
    }
    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        //提交前数据验证
        $json['warn'] = $this->dataValidation($info);
        if($json['warn'] !== true){
            goto resp;
        }
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此生产返工单';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此生产返工单不是草稿状态，不能提交';
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])){
                    $resultJson = $this->confirmEdit();
                    $json = json_decode($resultJson,true);
                    if ($json['warn'] != 2){
                        $this->rollback();
                        goto resp;
                    }
                }else {
                    self::insertOperateLog($info['id'],self::title,"提交");
                }
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '提交成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此' . self::title . '，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此' . self::title . '？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此' . self::title . '？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     *选择生产产品
     *
     * @return bool|string
     */
    public function addMaterial(): bool|string
    {
        if (optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard') {
            //生成生产流转卡
            $title = '生产流转卡编号';
        } else {
            $title = '生产派工单号';
        }
        $html =
            text(array("name" => "orderNo", "title" => $title)) .
            text(array('name' => 'code', 'title' => '产品编码')) .
            text(array('name' => 'materialName', 'title' => '产品名称')) .
            text(array('name' => 'model', 'title' => '产品型号'));
        $button = "<input style='margin-left: 5px' onclick=\"addMaterial()\" type='button' class='searchSub' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1100, "html" => $html, "button" => $button));
    }

    /**
     *添加物料
     */
    public function addMaterialSearch(): bool|string
    {
        if (optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard') {
            $json['html'] = $this->machiningCardSearch();
        } else {
            $and = " and workFlow = 0 and isClose=0 and machiningOrderId not in (select id from machining_order where coid = '" . self::$coid . "' and isClose = 1)";
            $mAnd = '';
            $like = [
                'orderNo' => $this->post('orderNo')
            ];
            $equal = [
                'coid' => self::$coid,
                'classify' => '生产派工',
                'state' => '已确认',
            ];

            if ($this->post('code')) {
                $mAnd .= " and code like '%" . $this->post('code') . "%'";
            }
            if ($this->post('materialName')) {
                $mAnd .= " and name like '%" . $this->post('materialName') . "%'";
            }
            if ($this->post('model')) {
                $mAnd .= " and model like '%" . $this->post('model') . "%'";
            }
            if ($mAnd) {
                $and .= " and materialId in (select id from material where 1=1 {$mAnd})";
            }
            $where = search(["like" => $like, "=" => $equal]) . $and;
            $page = $this->page([
                "table" => "machining_send_order",
                "where" => $where,
                'pageNum' => 50,
                "order" => "orderNo desc",
            ]);
            //获取表头
            $tr[] = ['', '生产派工单号', '单据日期', '生产线', '产品编码', '产品名称', '产品型号', '工序'];
            //获取记录
            foreach ($page['array'] as $array) {
                $material = query('material', "id = '$array[materialId]'");
                $line = query('product_line', "id = '$array[lineId]'");
                $process = query('process', "id = '$array[processId]'");
                $tr[] = array(
                    "<input name='mxId' value='$array[id]' type='radio'>",
                    $array['orderNo'],
                    $array['recordDate'],
                    $line['workshop'] . '-' . $line['name'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $process['name'],
                );
            }
            $json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        }

        return json_encode($json, 320);
    }

    /**
     * 生产流转卡
     */
    public function machiningCardSearch()
    {
        $and = " and a.sourceId not in (select id from machining_order where coid = '" . self::$coid . "' and isClose = 1)";
        $like = [
            'a.orderNo' => $this->post('orderNo'),
            'c.code' => $this->post('code'),
            'c.name' => $this->post('materialName'),
            'c.model' => $this->post('model'),
        ];
        $equal = [
            'a.coid' => self::$coid,
        ];
        $where = search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => "machining_card as a join machining_card_detail as b on a.id = b.orderId join material as c on c.id = a.materialId",
            'field' => "a.*,b.processId,b.id as mxId,c.name,c.code,c.model",
            "where" => $where,
            'pageNum' => 50,
            "order" => "a.orderNo desc,b.list asc",
        ]);
        //获取表头
        $tr[] = ['', '生产流转卡单号', '单据日期', '生产线', '工序', '产品编码', '产品名称', '产品型号'];
        //获取记录
        foreach ($page['array'] as $array) {
            $line = query('product_line', "id = '$array[lineId]'");
            $process = query('process', "id = '$array[processId]'");
            $tr[] = array(
                "<input name='mxId' value='$array[mxId]' type='radio'>",
                $array['orderNo'],
                $array['recordDate'],
                $line['workshop'] . '-' . $line['name'],
                $process['name'],
                $array['code'],
                $array['name'],
                $array['model'],
            );
        }
        return $page['hint'] . "<form name='mxForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'];
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMaterialEdit(): bool|string
    {
        $id = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($id)) {
            $json['warn'] = '请选择数据';
        } else {
            $json['preProcess'] = "";
            if (optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard') {
                $machining_card_detail = query('machining_card_detail', "id = '$id'");
                $sourceOrder = query('machining_card', "id = '$machining_card_detail[orderId]'");
                $routingDetail = query('routing_detail', "id = '$machining_card_detail[routingMxId]'");
                $process = query('process', "id = '$machining_card_detail[processId]'");
                $sourceId = $machining_card_detail['id'];
            } else {
                $sourceOrder = query('machining_send_order', "id = '$id'");
                $routingDetail = query('routing_detail', "id = '$sourceOrder[routingMxId]'");
                $process = query('process', "id = '$sourceOrder[processId]'");
                $sourceId = $sourceOrder['id'];
            }
            $line = query('product_line', "id = '$sourceOrder[lineId]'");
            $lineName = $line['workshop'] . '-' . $line['name'];
            $json['process'] = $process['name'];
            $json['processId'] = $process['id'];
            $json['valuationType'] = $routingDetail['valuationType'];
            $reportNum = find(array('table' => 'process_report', 'where' => "sendId = '$sourceId' and state = '已确认'", 'sum' => "yield"));
            $json['planNum'] = self::lostZero($reportNum, 'numPrecision');
            $json['unit'] = $sourceOrder['unit'];
            $json['materialName'] = materialClass::getName($sourceOrder['materialId']);
            $json['id'] = $id;
            $json['orderNo'] = $sourceOrder['orderNo'];
            $json['lineName'] = $lineName;

            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

	/**
	 * 批量打印
	 *
	 * @return string
	 */
	public function batchPrint(): string
	{
		$lists = $this->get('lists');
		if(empty($lists)){
			exit('参数错误');
		}else{
			$listId = base64_decode($lists, true);
			$array = explode(',', $listId);
			$data = [];
			foreach ($array as $id){
				$data[] = static::printPage($id, false);
			}
			return (new printTemplateClass())->start(self::page, $data);
		}
	}

	/**
	 * 打印
	 *
	 * @return string
	 */
	public function printPage($param = '', $isReturn = true): string|array
	{
		$id                  = $param ?: $this->get('id');
		$info                = query(self::table, " id = '$id'");
        if ($info['sourceTable'] == 'machining_card_detail') {
            $machining_card_detail = query('machining_card_detail', "id = '$info[sourceId]'");
            $sourceOrder = query('machining_card', "id = '$machining_card_detail[orderId]'");
            $machiningOrder = query('machining_order', "id = '$sourceOrder[sourceId]'");
        } else {
            $sourceOrder = query($info['sourceTable'], "id = '$info[sourceId]'");
            $machiningOrder = query('machining_order', "id = '$sourceOrder[machiningOrderId]'");
        }
        $material = query('material', "id = '$info[materialId]'");
        $info['companyName'] = query('company', "coid = '" . self::$coid . "'")['name']; //公司名称
        $info['title'] = self::title;
        $info['printTime'] = $this->time;
        $info['stid'] = self::findStaff($info['stid']);
        $info['checkId'] = '';
        $info['processTitle'] = '产品明细';
        $info['sourceNo'] = $machiningOrder['orderNo'];
        $process = query('process', "id = '$info[processId]'");
        $info['processName'] = $process['name'];
        $items[] = [
            'code' => $material['code'],
            'name' => $material['name'],
            'brand' => '',
            'model' => $material['model'],
            'num' => self::lostZero($info['num'], 'numPrecision'),
            'unit' => $info['unit'],
            'text'=>$info['text']
        ];
        $info['detail'] = $items;
	    if ($isReturn) {
		    return (new printTemplateClass())->start(self::page, $info);
	    } else {
		    return $info;
	    }
    }
}
